package com.miracle.controller;

import com.miracle.config.RestTemplateConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.List;

/**
 * @author jie.xi
 * @date 2022年05月11日 14:59
 */
@RestController
@Slf4j
public class UserController {

    @Autowired
    private DiscoveryClient discoveryClient;


    @Autowired
    private LoadBalancerClient loadBalancerClient;

    @Autowired
    private RestTemplate restTemplate;

    @GetMapping("/user/showProductMsg")
    public String showProductMsg(){
        //1. 第一种服务端调用方式
        RestTemplate restTemplate = new RestTemplate();
        String msg = restTemplate.getForObject("http://localhost:9998/product/showMsg", String.class);
        log.info("调用成功返回的信息：[{}]",msg);
        return msg;
    }

    @GetMapping("/user/showAllProductMsg")
    public String showAllProductMsg(){
//        RestTemplate restTemplate = new RestTemplate();
//        String msg = restTemplate.getForObject("http://localhost:9998/product/findAll", String.class);
//        log.info("调用成功返回的信息：[{}]",msg);

        //ribbon 调用方式 discoveryClient  loadBalanceClient  @LoadBalance
        List<ServiceInstance> productsClients = discoveryClient.getInstances("productsClient");
        for (ServiceInstance productsClient : productsClients) {
            System.out.println(productsClient.getHost());
            System.out.println(productsClient.getPort());
        }

        //loadBalance client
        ServiceInstance productsClient = loadBalancerClient.choose("productsClient");
        System.out.println(productsClient.getHost());
        System.out.println(productsClient.getPort());
        RestTemplate restTemplate2 = new RestTemplate();
        String msg2 = restTemplate2.getForObject("http://"+productsClient.getHost()+":"+productsClient.getPort()+"/product/showMsg", String.class);

        //4. @LoadBalance + RestTemplate
        String msg3 = restTemplate.getForObject("http://productsClient/product/showMsg", String.class);
        return msg3;
    }
}
